const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const {uploadFile} = require('./uploadHelper')
const assetsBase = path.resolve(__dirname,'../src/static')//本地文件夹路径
const cosBase = process.cwd().replace(/\\/g,'/').split('/').pop()//上传到bucket上的文件夹名称


let failArr = []
let successArr = []

//递归上传文件夹
async function uploadDir(dirPath,parent=''){
    const files = fs.readdirSync(dirPath);
    for (let index = 0; index < files.length; index++) {
        const file = files[index];
        let cp = path.resolve(dirPath,file);
        let fileStat = fs.statSync(cp);
        if(fileStat.isDirectory()){
            await uploadDir(cp,`${parent}/${file}`);
        }else{
            let cosPath = `${parent}/${file}`
            try {
                await uploadFile(cp,cosPath)
                console.log(chalk.green(`${cosPath}上传成功`));
                successArr.push(cosPath)
            } catch (error) {
                console.log(chalk.red(`${cosPath}上传失败`));
                failArr.push(cosPath)
            }
        }
    }
}

async function start(){
    failArr = []
    successArr =[]
    await uploadDir(assetsBase,cosBase);
    if(failArr.length){
        console.log(chalk.red.bold(`上传完毕，${successArr.length}个成功，${failArr.length}个失败,失败文件如下，请检查`));
        console.log(failArr.join(',\n'));
    }else{
        console.log(chalk.green.bold(`上传完毕，${successArr.length}个成功，${failArr.length}个失败`));
    }
}
start()
